package br.biofoco.p2p.peer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import com.google.inject.Singleton;

@Singleton
public final class JsonPeerSerializer implements PeerSerializer {
	
	/* (non-Javadoc)
	 * @see br.biofoco.p2p.peer.PeerSerializer#serializeCollection(java.util.Collection)
	 */
	public String serialize(Collection<? extends PeerNode> peers) throws IOException {			
		List<PeerConfig> config = new ArrayList<PeerConfig>();		
		for (PeerNode p : peers) {
			config.add(p.getPeerConfig());
		}		
		ObjectMapper mapper = new ObjectMapper();				
		return mapper.writeValueAsString(config);
	}	

	/* (non-Javadoc)
	 * @see br.biofoco.p2p.peer.PeerSerializer#serializePeer(br.biofoco.p2p.peer.PeerNode)
	 */
	public String serialize(PeerNode p) throws IOException {
		ObjectMapper mapper = new ObjectMapper();		
		return mapper.writeValueAsString(p.getPeerConfig());
	}

	/* (non-Javadoc)
	 * @see br.biofoco.p2p.peer.PeerSerializer#unserializePeer(java.lang.String)
	 */
	public PeerNode unserialize(String content) throws IOException {		
		ObjectMapper mapper = new ObjectMapper();		
		PeerConfig obj = mapper.readValue(content, PeerConfig.class);		
		return new ProxyPeer(obj);
	}
	
	/* (non-Javadoc)
	 * @see br.biofoco.p2p.peer.PeerSerializer#unserializeCollection(java.lang.String)
	 */
	public Collection<? extends PeerNode> unserializeCollection(String content) throws IOException {
		
		ObjectMapper mapper = new ObjectMapper();
		List<PeerConfig> peerConfigList = mapper.readValue(content, new TypeReference<ArrayList<PeerConfig>>() {});
		
		List<PeerNode> peerNodeList = new ArrayList<PeerNode>(peerConfigList.size());
		for (Object obj : peerConfigList) {			
			peerNodeList.add(new ProxyPeer((PeerConfig) obj));			
		}		
		return peerNodeList;
	}

}
